class Solution:
    def findOrder(self, numCourses: int, prerequisites: List[List[int]]) -> List[int]:
        res = []
        g = [set() for _ in range(numCourses)]
        indegrees = [0] * numCourses
        for prerequisite in prerequisites:
            w = prerequisite[0]
            v = prerequisite[1]
            g[v].add(w)
            indegrees[w] += 1
        queue = collections.deque([])
        for i in range(numCourses):
            if indegrees[i] == 0:
                queue.append(i)
        index = 0
        while queue:
            v = queue.popleft()
            res.append(v)
            index += 1
            for w in g[v]:
                indegrees[w] -= 1
                if indegrees[w] == 0:
                    queue.append(w)
        if index != numCourses:
            res = []
        return res